package com.fire.user.util.wx.wxPush;

import com.fire.user.util.JkWxUtils;
import com.fire.user.util.wx.HttpsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.fire.core.util.AjaxResult;
import com.fire.user.constants.ErrorCodeConstants;

@Component
public class UserUtil {

	private static Logger log = LoggerFactory.getLogger(UserUtil.class);
	
	@Value("${weChat.subscribeStateUrl}")
	private String subscribeStateUrl;
	@Value("${weChat.switch}")
	private String type;
	@Autowired
	TokenUtil tokenUtil;
	@Autowired
	private HttpsUtil httpsUtil;
	@Autowired
	private JkWxUtils jkWxUtils;
	
    /**
     * 根据微信openId 获取用户是否订阅
     * @param openId 微信openId
     * @return 是否订阅该公众号标识
     */
	
    public Integer subscribeState(String openId,String appId,String appSecret){
    	String accessToken = "";
    	//1表示accesstoken、ticket向金科请求，2表示向微信请求
    	if("1".equals(type)) {
    		AjaxResult result = jkWxUtils.getJKAccessToken();
    		if(ErrorCodeConstants.SUCCESS.equals(result.getStatus())) {
    			accessToken = (String)result.getContext();
    		}
    	}else {
    		accessToken = tokenUtil.getWXToken(appId,appSecret).getAccessToken();
    	}
        String tmpurl = subscribeStateUrl + "access_token=" + accessToken +"&openid="+openId;
        log.info("获取的openid是:"+openId);
       
        JSONObject result = httpsUtil.httpsRequest(tmpurl, "GET",null);
        JSONObject resultJson = new JSONObject(result);
        log.info("获取用户是否订阅 errcode:{} errmsg:{}", resultJson.getInteger("errcode"), resultJson.getString("errmsg"));
        String errmsg = (String) resultJson.get("errmsg");
        if(errmsg==null){
            //用户是否订阅该公众号标识（0代表此用户没有关注该公众号 1表示关注了该公众号）。
            Integer subscribe = (Integer) resultJson.get("subscribe");
            return subscribe;
        }
        return -1;
    }
}
